package org.marsdonne.sync.messenger;

import org.hibernate.exception.ConstraintViolationException;
import org.marsdonne.sync.Event;
import org.marsdonne.sync.Record;
import org.marsdonne.sync.RecordRepos;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class SyncedRecorder {

    @Resource
    private RecordRepos repos;

    @JmsListener(
            containerFactory = "syncedRecorderListenerFactory", concurrency = "1-5",
            destination = "${sync.artemis.channel:channels.sync}")
    public void receive(Event event) {
        try {
            repos.save(new Record(event.getVersion(), event.getAction(), event.getDomain(), event.getContent(), event.getDateSynced()));
        } catch (Exception ex) {
            if (ex != null && ex.getCause() != null && ex.getCause() instanceof ConstraintViolationException) {
                /*Idempotent by unique constraint*/
            } else {
                ex.printStackTrace();
            }
        }
    }
}
